package com.djc.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.djc.pojo.user;
import com.djc.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @ResponseBody
    @RequestMapping(value = "/query",produces = "text/plain;charset=UTF-8")
    public String query(@RequestParam(value = "name",required = false)String name){
        List<user> list = userService.query(name);
        String json= JSONObject.toJSONString(list);
        System.out.println(json);
        return json;
    }

    //添加用户
    @RequestMapping("/add")
    @ResponseBody
    public String add(user user){
        userService.add(user);
        return "1";
    }

    //删除用户
    @RequestMapping("/delete")
    @ResponseBody
    public String delete(Integer id){
        userService.delete(id);
        return "1";
    }

    //根据id查询用户
    @RequestMapping(value = "edit",produces = "text/plain;charset=UTF-8")
    @ResponseBody
    public String edit(Integer id){
        user user=userService.edit(id);
        System.out.println(user);
        return JSONArray.toJSONString(user);
    }

    //修改用户
    @RequestMapping("/update")
    @ResponseBody
    public String update(user user){
        userService.update(user);
        return "redirect:query";
    }

    //登录
    @RequestMapping("/login")
    @ResponseBody
    public ModelAndView login(@RequestParam(value = "name" ,required = false) String name, @RequestParam(value = "password",required = false) String password, HttpSession session,
                              RedirectAttributes attributes) {
        ModelAndView modelAndView = new ModelAndView();
        user user = userService.login(name, password);
        if (user != null) {
            modelAndView.setViewName("/index.html");
            return modelAndView;
        } else {
            attributes.addFlashAttribute("message", "用户名或密码错误！");
            modelAndView.setViewName("/login.html");
            return modelAndView;
        }
    }
}
